package web;

import com.wf.captcha.utils.CaptchaUtil;
import dao.LoginDao;
import entity.User;
import utils.Constant;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServer extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/login.html");
        requestDispatcher.forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8;");
        String captcha = req.getParameter("captcha");
        System.out.println(captcha);
        if (CaptchaUtil.ver(captcha,req)){
            CaptchaUtil.clear(req);
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            try {
                User loginUser = new LoginDao().selectByUsernameAndPassword(username, password);
                if (loginUser == null){
                    resp.sendRedirect(req.getContextPath() + "/error");
                    resp.getWriter().write("<h3 style='color:red;'>登陆失败</h3><a href='/login'>请重新登录</a>");
                }else {
                    //将登陆的用户存储到sessionr
                    HttpSession session = req.getSession();
                    session.setAttribute(Constant.LOGIN_SESSION,new User(username));
                    resp.getWriter().write("<h3 style='color:green;'>登录成功</h3>");
                    resp.sendRedirect(req.getContextPath() + "/index");
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }else {
            resp.getWriter().write("<h3 style='color:red;'>验证码错误</h3><a href='/login'>请重新登录</a>");
        }
    }
}
